package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import sun.jdbc.rowset.CachedRowSet;



public class Database {
	static {
		try {
			DriverManager.registerDriver(new org.gjt.mm.mysql.Driver());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	//ȡ������
	private static Connection getConnection() {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/moviemanage?useUnicode=true&characterEncoding=utf8","root","123456");
			if(conn==null)
			{
				System.out.println("null");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	//������
	public static void execute(String sql) {
		Connection conn = getConnection();

		try {
			PreparedStatement stmt = conn.prepareStatement(sql);
			stmt.executeUpdate(sql);
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	//��ѯ���
	public static ResultSet query(String sql) {
		Connection conn =  getConnection();
		PreparedStatement stmt = null;
		CachedRowSet crs=null;
		try {
			crs = new CachedRowSet();
			stmt = conn.prepareStatement(sql);
			ResultSet rs  = stmt.executeQuery(sql);
			crs.populate(rs);
			
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return crs;
	}
	
	//ɾ�����
	public static void delete(String sql){
		Connection conn = getConnection();
		try{
			PreparedStatement stmt = conn.prepareStatement(sql);
			stmt.executeUpdate(sql);
		    stmt.close();
		    conn.close();
		}
		catch(SQLException e){
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		System.out.println(getConnection());
	}
}
